package webserver;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;

public class Processor extends Thread {
	
	private static final String PATH="E:\\02_workspace\\01_eclipse_workspace\\webserver\\webfile\\";
	
	private Socket socket;
	
	private InputStream in;
	
	private PrintStream out;
	
	public Processor(){}
	
	public Processor(Socket socket){
		this.socket=socket;
		try {
			in=socket.getInputStream();
			out=new PrintStream(socket.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void run() {
		sendFile(parse(in));
	}
	
	/**
	 * 从socket输入流中获取文件名称
	 * @param in 输入流
	 * @return 返回请求的文件名称
	 */
	public String parse(InputStream in){
		String fileName=null;
		BufferedReader br=new BufferedReader(new InputStreamReader(in));
		try {
			String httpMessage=br.readLine();
			System.out.println("请求头:"+httpMessage);
			if (httpMessage==null) {
				return null;
			}
			String[] content=httpMessage.split(" ");
			if (content.length!=3) {
				this.sendErrorMessage(400, "client query error!");
				return null;
			}
			System.out.println("code:"+content[0]+",page:"+content[1]+",content:"+content[2]);
			fileName=content[1];
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return fileName;
	}
	
	/**
	 * 发送错误消息
	 * @param code
	 * @param message
	 */
	public void sendErrorMessage(int code, String message){
		out.println("HTTP/1.0 "+code+" "+message);
		out.println("content-type: text/html");
		out.println("<html>");
		out.println("<head>");
		out.println("<title>");
		out.println(code);
		out.println("</title>");
		out.println("</head>");
		out.println("<body>");
		out.println("<h1>");
		out.println("errorcode:"+code+"   errorMessage: "+message);
		out.println("<h1>");		
		out.println("</body>");
		out.println("</html>");
		try {
			out.flush();
			out.close();
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 向客户端返回请求的文件
	 * @param fileName
	 */
	public void sendFile(String fileName){
		System.out.println("文件名："+fileName);
		if (fileName==null||fileName.trim().length()==0||fileName.equals("/")) {
			fileName="404.html";
		}
		File file=new File(this.PATH+fileName);
		System.out.println("文件路径:"+file.getPath());
		if (!file.exists()) {
			sendErrorMessage(404, "File not found!");
			return;
		}
		
		try {
			in =new FileInputStream(file);
			byte[] content=new byte[((int)file.length())];
			in.read(content);
			out.println("HTTP/1.1 200 queryfile ");
			out.println("content-length:"+content.length);
			out.println();
			out.write(content);
			out.flush();
			out.close();
			in.close();
		} catch (Exception e) {
			e.printStackTrace();
			sendErrorMessage(404,"server exception!");
		} 
		
	}
	
}
